package cn.edu.ujn.bmis.action;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import cn.edu.ujn.bmis.model.Book;
import cn.edu.ujn.bmis.model.OrderBook;
import cn.edu.ujn.bmis.model.SysPara;
import cn.edu.ujn.bmis.model.UserInfo;
import cn.edu.ujn.bmis.service.BookManager;
import cn.edu.ujn.bmis.service.OrderBookManager;
import cn.edu.ujn.bmis.service.SysParaManager;
import cn.edu.ujn.bmis.service.UserInfoManager;
import cn.edu.ujn.bmis.tools.Constant;
import cn.edu.ujn.bmis.tools.Helper;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Component("OrderBook")
@Scope("prototype")
public class OrderBookAction extends ActionSupport {

	private static final long serialVersionUID = -8663199752704629159L;
	private OrderBookManager orderBookManager;
	private OrderBook orderBook;
	private String bookName;
	private String author;
	private String press;
	private String bookType;
	private Helper helper;
	private int pageNum = 1;
	private int currentPage = 1; // 当前是第几页
	private int totalCount = 0; // 总条数
	private int numPerPage = 5; // 每页显示多少条
	private int pageNumShown = 5; // 页标数字多少个
	private int pageCount = 0; // 总页数
	private String orderField;
	private String orderDirection;
	private String targetType = "navTab"; // navTab或dialog，用来标记是navTab上的分页还是dialog上的分页
	private BookManager bookManager;
	private List<Book> bookList = new ArrayList<Book>();
	private SysParaManager sysParaManager;
	private List<SysPara> sysParaList = new ArrayList<SysPara>();
	private List<OrderBook> orderBookList = new ArrayList<OrderBook>();
	private String startTime;
	private String endTime;
	private int id;
	private String functionNum;
	private String readerId;
	private UserInfoManager userInfoManager;
	private String bookId;
	private Book book;
	
	/**
	 * orderTime!=null endOrderTime!=null effective=1 表示预约有效
	 * orderTime==null endOrderTime==null effective=0 表示取消预约
	 * orderTime!=null endOrderTime!=null effective=0 表示预约的图书被借走了，预约过程完成使命
	 * 
	 */
	
	
	
	/**
	 * 管理员查看预约图书
	 */
	@SuppressWarnings("unchecked")
	public String findAdOrderBook(){
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		String hql="";
		String hql_size="";
		String hql_type="";
		
		hql_type="select s.value from SysPara s where s.name='图书种类'";
		sysParaList=sysParaManager.findSysPara(hql_type);
		this.currentPage = this.pageNum;
		hql="select o from OrderBook o,Book b,UserInfo u where o.userInfo.userId=u.userId and o.book.bookId=b.bookId and o.orderTime!=null and o.effective=1 ";
		hql_size="select count(*) from OrderBook o,Book b,UserInfo u where o.userInfo.userId=u.userId and o.book.bookId=b.bookId and o.orderTime!=null and o.effective=1 ";
		if(readerId!=null&&!"".equals(readerId)){
			hql+=" and o.userInfo.userId='"+readerId.trim()+"' ";
			hql_size+=" and o.userInfo.userId='"+readerId.trim()+"' ";
		}
		if(bookType!=null&&!"".equals(bookType)){
			hql+=" and o.book.bookType='"+bookType.trim()+"' ";
			hql_size+=" and o.book.bookType='"+bookType.trim()+"' ";
		}
		if(startTime!=null&&!"".equals(startTime)&&endTime!=null&&!"".equals(endTime)){
			hql+=" and o.orderTime  between CONVERT(datetime, '"+startTime.trim()+"') and CONVERT(datetime, '"+endTime.trim()+"')";
			hql_size+=" and o.orderTime between CONVERT(datetime, '"+startTime.trim()+"') and CONVERT(datetime, '"+endTime.trim()+"')";
		}
		totalCount = helper.findSize(hql_size);
		pageCount = totalCount % numPerPage == 0 ? totalCount / numPerPage
				: totalCount / numPerPage + 1;
		orderBookList = helper.fenYe(hql, this.currentPage, this.numPerPage);
		return SUCCESS;
	}
	
	/**
	 * 进入添加预约页面
	 */
	public String beforeAddOrderBook(){
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		String hql = "from Book b where b.bookId=" + bookId.trim() + "";
		bookList=bookManager.findBook(hql);
		if (bookList.size() > 0) {
			book = bookList.get(0);
		}
		return SUCCESS;
	}
	
	/**
	 * 管理员预约图书
	 */
	public void addAdOrderBook() {
		String hql_check = "";
		List<UserInfo> userInfoList = new ArrayList<UserInfo>();
		hql_check = "from UserInfo u where u.userId='" + orderBook.getUserInfo().getUserId() + "'";
		userInfoList = userInfoManager.findUserInfo(hql_check);
		if (userInfoList.size() <= 0) {
			Helper.out("300", "输入的读者编号不存在请检查！", "", "", "", "");
			return;
		}
		String now = "";
		Date today = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		now = dateFormat.format(today);
		orderBook.setOrderTime(now);
		orderBook.setEffective(1);
		//预约到期时间
		Calendar cal = new GregorianCalendar();
		cal.setTime(today);
		cal.add(Calendar.DATE,Constant.orderDay);
		Date d = cal.getTime();
		String endOrderTime = dateFormat.format(d);
		orderBook.setEndOrderTime(endOrderTime);
		if (orderBookManager.addOrderBook(orderBook)) {
			Helper.out("200", "图书预约成功", "closeCurrent", "", "", "findAdBeforeOrderBook");
		} else {
			Helper.out("300", "图书预约失败", "", "", "", "");
		}
	}

	/**
	 * 预约图书
	 */
	@SuppressWarnings("unchecked")
	public void addOrderBook() {
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
			return;
		}
		String now = "";
		Date today = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		now = dateFormat.format(today);
		Map session = (Map) ActionContext.getContext().getSession();
		UserInfo users = new UserInfo();
		users = (UserInfo) session.get("user");
		orderBook.setUserInfo(users);
		orderBook.setOrderTime(now);
		orderBook.setEffective(1);
		//预约到期时间为7天
		Calendar cal = new GregorianCalendar();
		cal.setTime(today);
		cal.add(Calendar.DATE,Constant.orderDay);
		Date d = cal.getTime();
		String endOrderTime = dateFormat.format(d);
		orderBook.setEndOrderTime(endOrderTime);
		if (orderBookManager.addOrderBook(orderBook)) {
			Helper.out("200", "图书预约成功", "", "", "manageOrderBook", "");
		} else {
			Helper.out("300", "图书预约失败", "", "", "", "");
		}
	}

	/**
	 * 预约之前查看可以预约的图书
	 */
	@SuppressWarnings("unchecked")
	public String findBeforeOrderBook() {
		String hql = "";
		String hql_size = "";
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		this.currentPage = this.pageNum;
		hql = "select b from Book b,Donator d where b.borrowOK=1 and b.donator.donatorId=d.donatorId "
				+ "and not exists(select 1 from OrderBook o where b.bookId=o.book.bookId "
				+ "and o.effective=1)";
		hql_size = "select count(*) from Book b,Donator d where b.borrowOK=1 and b.donator.donatorId=d.donatorId "
				+ "and not exists(select 1 from OrderBook o where b.bookId=o.book.bookId "
				+ "and o.effective=1)";
		if (bookName != null && !"".equals(bookName)) {
			hql += " and b.bookName='" + bookName.trim() + "'";
			hql_size += " and b.bookName='" + bookName.trim() + "'";
		}
		if (author != null && !"".equals(author)) {
			hql += " and b.author='" + author.trim() + "'";
			hql_size += " and b.author='" + author.trim() + "'";
		}
		if (press != null && !"".equals(press)) {
			hql += " and b.press='" + press.trim() + "'";
			hql_size += " and b.press='" + press.trim() + "'";
		}
		if (bookType != null && !"1".equals(bookType)) {
			hql += " and b.bookType='" + bookType.trim() + "'";
			hql_size += " and b.bookType='" + bookType.trim() + "'";
		}
		totalCount = helper.findSize(hql_size);
		pageCount = totalCount % numPerPage == 0 ? totalCount / numPerPage
				: totalCount / numPerPage + 1;
		bookList = helper.fenYe(hql, this.currentPage, this.numPerPage);
		// 查找图书种类
		String hql_type = "";
		hql_type = "select s.value from SysPara s where s.name='图书种类'";
		sysParaList = sysParaManager.findSysPara(hql_type);
		return SUCCESS;
	}
	
	/**
	 * orderTime!=null effective=1 表示预约有效
	 * orderTime==null effective=0 表示取消预约
	 * orderTime!=null effective=0 表示预约的图书被借走了，预约过程完成使命
	 * 
	 */

	/**
	 * 查看可以取消预约的记录
	 */
	@SuppressWarnings("unchecked")
	public String findDelOrderBook() {
		String hql = "";
		String hql_size = "";
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		this.currentPage = this.pageNum;
		hql = "select o from Book b,OrderBook o where b.bookId=o.book.bookId and o.orderTime!=null and o.effective=1";
		hql_size = "select count(*) from Book b,OrderBook o where b.bookId=o.book.bookId and o.orderTime!=null and o.effective=1";
		if (startTime != null && !"".equals(startTime) && endTime != null
				&& !"".equals(endTime)) {
			hql += " and o.orderTime between CONVERT(datetime, '"
					+ startTime.trim() + "') and CONVERT(datetime, '"
					+ endTime.trim() + "')";
			hql_size += " and o.orderTime between CONVERT(datetime, '"
					+ startTime.trim() + "') and CONVERT(datetime, '"
					+ endTime.trim() + "')";
		}
		if (bookName != null && !"".equals(bookName)) {
			hql += " and o.book.bookName='" + bookName.trim() + "'";
			hql_size += " and o.book.bookName='" + bookName.trim() + "'";
		}
		totalCount = helper.findSize(hql_size);
		pageCount = totalCount % numPerPage == 0 ? totalCount / numPerPage
				: totalCount / numPerPage + 1;
		orderBookList = helper.fenYe(hql, this.currentPage, this.numPerPage);
		return SUCCESS;
	}

	/**
	 * 取消预约
	 */
	public void delOrderBook() {
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		String hql = "";
		hql = "update OrderBook o set o.orderTime=null,o.effective=0,o.endOrderTime=null where o.id='"
				+ id + "'";
		if (orderBookManager.updateOrderBook(hql)) {
			Helper.out("200", "图书解约成功", "", "", "manageDelOrderBook", "");
		} else {
			Helper.out("300", "图书解约失败", "", "", "", "");
		}
	}
	
	/**
	 * 进入修改预约界面
	 */
	public String beforeUpdateOrderBook(){
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		String hql = "from OrderBook o where o.id=" + id + "";
		orderBookList = orderBookManager.findOrderBook(hql);
		if (orderBookList.size() > 0) {
			orderBook = orderBookList.get(0);
		}
		return SUCCESS;
	}
	
	public void updateOrderBook(){
		String hql_check = "";
		List<UserInfo> userInfoList = new ArrayList<UserInfo>();
		hql_check = "from UserInfo u where u.userId='" + orderBook.getUserInfo().getUserId() + "'";
		userInfoList = userInfoManager.findUserInfo(hql_check);
		if (userInfoList.size() <= 0) {
			Helper.out("300", "输入的读者编号不存在请检查！", "", "", "", "");
			return;
		}
		//预约到期时间
	
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			Date orderTime;
			orderTime = dateFormat.parse(orderBook.getOrderTime());
			Calendar cal = new GregorianCalendar();
			cal.setTime(orderTime);
			cal.add(Calendar.DATE,Constant.orderDay);
			Date d = cal.getTime();
			String endOrderTime = dateFormat.format(d);
			orderBook.setEndOrderTime(endOrderTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		if(orderBookManager.updateOrderBook(orderBook)){
			Helper.out("200", "预约图书修改成功", "closeCurrent", "", "", "findAdOrderBook");
		}else{
			Helper.out("300", "预约图书修改失败", "", "", "", "");
		}
	}
	

	public OrderBookManager getOrderBookManager() {
		return orderBookManager;
	}

	@Resource(name = "orderBookManager")
	public void setOrderBookManager(OrderBookManager orderBookManager) {
		this.orderBookManager = orderBookManager;
	}

	public OrderBook getOrderBook() {
		return orderBook;
	}

	public void setOrderBook(OrderBook orderBook) {
		this.orderBook = orderBook;
	}

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getPress() {
		return press;
	}

	public void setPress(String press) {
		this.press = press;
	}

	public String getBookType() {
		return bookType;
	}

	public void setBookType(String bookType) {
		this.bookType = bookType;
	}

	public Helper getHelper() {
		return helper;
	}

	@Resource(name = "helper")
	public void setHelper(Helper helper) {
		this.helper = helper;
	}

	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public int getNumPerPage() {
		return numPerPage;
	}

	public void setNumPerPage(int numPerPage) {
		this.numPerPage = numPerPage;
	}

	public int getPageNumShown() {
		return pageNumShown;
	}

	public void setPageNumShown(int pageNumShown) {
		this.pageNumShown = pageNumShown;
	}

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public String getOrderField() {
		return orderField;
	}

	public void setOrderField(String orderField) {
		this.orderField = orderField;
	}

	public String getOrderDirection() {
		return orderDirection;
	}

	public void setOrderDirection(String orderDirection) {
		this.orderDirection = orderDirection;
	}

	public String getTargetType() {
		return targetType;
	}

	public void setTargetType(String targetType) {
		this.targetType = targetType;
	}

	public BookManager getBookManager() {
		return bookManager;
	}

	@Resource(name = "bookManager")
	public void setBookManager(BookManager bookManager) {
		this.bookManager = bookManager;
	}

	public List<Book> getBookList() {
		return bookList;
	}

	public void setBookList(List<Book> bookList) {
		this.bookList = bookList;
	}

	public SysParaManager getSysParaManager() {
		return sysParaManager;
	}

	@Resource(name = "sysParaManager")
	public void setSysParaManager(SysParaManager sysParaManager) {
		this.sysParaManager = sysParaManager;
	}

	public List<SysPara> getSysParaList() {
		return sysParaList;
	}

	public void setSysParaList(List<SysPara> sysParaList) {
		this.sysParaList = sysParaList;
	}

	public List<OrderBook> getOrderBookList() {
		return orderBookList;
	}

	public void setOrderBookList(List<OrderBook> orderBookList) {
		this.orderBookList = orderBookList;
	}

	public String getStartTime() {
		return startTime;
	}

	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	public String getEndTime() {
		return endTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFunctionNum() {
		return functionNum;
	}

	public void setFunctionNum(String functionNum) {
		this.functionNum = functionNum;
	}

	public String getReaderId() {
		return readerId;
	}

	public void setReaderId(String readerId) {
		this.readerId = readerId;
	}

	public UserInfoManager getUserInfoManager() {
		return userInfoManager;
	}

	@Resource(name="userInfoManager")
	public void setUserInfoManager(UserInfoManager userInfoManager) {
		this.userInfoManager = userInfoManager;
	}

	public String getBookId() {
		return bookId;
	}

	public void setBookId(String bookId) {
		this.bookId = bookId;
	}

	public Book getBook() {
		return book;
	}

	public void setBook(Book book) {
		this.book = book;
	}
	
}
